import { AppRequest } from "../wrap/request";
import { APIRequest as APIRequestTool } from "./tool";

import type { CommonRes } from "@/typings/common";
import type { RequestDefaultConfig } from "../request.type";

interface UseRequestRes {
    run: () => Promise<CommonRes<any>[]>;
    request: AppRequest[];
}

function useGlobalRequest() {
    const _globalReqMap: Map<string, AppRequest> = new Map();

    // 删除
    const _remove = (uuid: string) => {
        let flag = _globalReqMap.delete(uuid);
        // if (!flag) {
        //     console.log(`删除了一个 不存在的 ${uuid} 请求`);
        // }
    };
    const _pushReq = (req: AppRequest) => {
        _globalReqMap.set(req.uuid, req);
    };

    const reset = () => {
        // 遍历
        _globalReqMap.forEach((v) => {
            v.cancel();
        });
        // 清空
        _globalReqMap.clear();
    };
    // 请求
    const APIRequest = (...args: RequestDefaultConfig[]): UseRequestRes => {
        return APIRequestTool(
            args,
            function push(item: AppRequest) {
                _pushReq(item);
            },
            function remove(uuid: string) {
                _remove(uuid);
            }
        );
    };

    return {
        reset,
        APIRequest,
    };
}

const { APIRequest, reset } = useGlobalRequest();
const GlobalRequest = {
    request: APIRequest,
    reset,
};

export { GlobalRequest };
